package com.oreilly.android.taskmanager;

import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Locale;

import com.oreilly.android.taskmanager.tasks.Task;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Address;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.ToggleButton;

public class AddTaskActivity extends TaskManagerActivity {

	private static final int REQUEST_CHOOSE_ADDRESS = 0;
	private EditText taskTitleEditText;
	private EditText taskDescriptionEditText;
	private boolean changesPending;
	private AlertDialog unsavedChangesDialog;
	private Address address;
	private DatePicker dueDateDatePicker;
	private ToggleButton dueDateToggleButton;

	private int year;
	private int month;
	private int day;

	private boolean editingTask;
	private Task task;

	private TaskManagerApplication app;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		editingTask = false;
		setContentView(R.layout.edit_tasks);
		Bundle bundle = getIntent().getExtras();

		app = (TaskManagerApplication) getApplication();

		setUpViews();

		Bundle extras = getIntent().getExtras();
		if (extras != null) {
			long id = bundle.getLong("TASK_ID");
			Log.d("TaskManager", "Task ID: " + id);
			if (id != 0) {
				editingTask = true;
				task = app.findTask(id);
				taskTitleEditText.setText(task.getTitle());
				taskDescriptionEditText.setText(task.getDescription());
				Date date = task.getDueDate();
				if (date != null)
					setDate(task.getDueDate());
			}
		} else {
			task = new Task();
		}
	}

	@Override
	protected void onResume() {
		super.onResume();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		MenuInflater inflator = getMenuInflater();
		inflator.inflate(R.menu.edit_task_menu, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.add_location:
			addLocationToTask();
			break;
		case R.id.set_category:
			// TODO: Add set category function
			break;
		}
		return true;
	}

	protected void addLocationToTask() {
		Intent intent = new Intent(AddTaskActivity.this,
				AddLocationMapActivity.class);
		startActivityForResult(intent, REQUEST_CHOOSE_ADDRESS);
	}

	private void setUpViews() {
		taskTitleEditText = (EditText) findViewById(R.id.task_title_edittext);
		taskDescriptionEditText = (EditText) findViewById(R.id.task_description_edittext);

		taskTitleEditText.addTextChangedListener(new TextWatcher() {

			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				changesPending = true;
			}

			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
			}

			public void afterTextChanged(Editable s) {
			}
		});
		taskDescriptionEditText.addTextChangedListener(new TextWatcher() {
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				changesPending = true;
			}

			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
			}

			public void afterTextChanged(Editable s) {
			}
		});

		dueDateDatePicker = (DatePicker) findViewById(R.id.due_date_datepicker);
		dueDateToggleButton = (ToggleButton) findViewById(R.id.due_date_togglebutton);
	}

	protected void setDate(int year, int monthOfYear, int dayOfMonth) {
		dueDateDatePicker.updateDate(year, month, dayOfMonth);
	}

	protected void setDate(Date dueDate) {
		int year = dueDate.getYear();
		int month = dueDate.getMonth();
		int day = dueDate.getDay();
		setDate(year, month, day);
	}

	protected void addTask() {
		String title = taskTitleEditText.getText().toString();
		if (!title.equals("")) {
			String description = taskDescriptionEditText.getText().toString();

			task.setTitle(title);
			task.setDescription(description);
			task.setDueDate(year, month, day);

			if (address != null) {
				task.setLatitude(address.getLatitude());
				task.setLongitude(address.getLongitude());
				String location = "";
				for (int i = 0; i < address.getMaxAddressLineIndex(); i++) {
					location = address.getAddressLine(i);
				}
				task.setLocation(location);
			} else {
				task.setLocation(null);
			}

			if (dueDateToggleButton.isChecked()) {
				int year = dueDateDatePicker.getYear();
				int month = dueDateDatePicker.getMonth();
				int day = dueDateDatePicker.getDayOfMonth();
				task.setDueDate(year, month, day);
			}

			Log.d("TaskManager", "Editing Task: " + editingTask);
			if (editingTask) {
				app.saveTask(task);
			} else {
				app.addTask(task);
			}
			setResult(RESULT_OK);
		}
		finish();
	}

	protected void cancel() {
		if (changesPending) {
			unsavedChangesDialog = new AlertDialog.Builder(this)
					.setTitle(R.string.unsaved_changes_title)
					.setMessage(R.string.unsaved_changes_message)
					.setPositiveButton(R.string.add_task,
							new AlertDialog.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int which) {
									addTask();
								}
							})
					.setNeutralButton(R.string.discard,
							new AlertDialog.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int which) {
									finish();
								}
							})
					.setNegativeButton(R.string.cancel,
							new AlertDialog.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int which) {
									unsavedChangesDialog.cancel();
								}
							}).create();
			unsavedChangesDialog.show();
		} else {
			finish();
		}
	}

	public void addTaskButtonClicked(View view) {
		addTask();
	}

	public void cancelButtonClicked(View view) {
		cancel();
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (REQUEST_CHOOSE_ADDRESS == requestCode && RESULT_OK == resultCode) {
			address = data
					.getParcelableExtra(AddLocationMapActivity.ADDRESS_RESULT);
			String line = address.getAddressLine(0);

			// TODO: NOTIFIY USER OF ADDRESS ON VIEW
		} else {
			super.onActivityResult(requestCode, resultCode, data);
		}
	}

}
